package com.movie.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.movie.util.SessionUtil;
import com.zhenzi.sms.ZhenziSmsClient;

/**
 * Servlet implementation class SendSmsServlet
 */
@WebServlet("/SendSmsServlet")
public class SendSmsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SendSmsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("进入servlet");
		try {
			String number = request.getParameter("phone");
			String testbtn=request.getParameter("testbtn");
			System.out.println(testbtn);
			//String templateId = request.getParameter("templateId");
			JSONObject json = null;
			//生成6位验证码
			//String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
			//System.out.print("验证码: "+verifyCode);
			//发送短信
			ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "110305", "334e369f-0ebe-4bfb-91e1-91872efe94fd");
			Map<String, Object> params = new HashMap<String, Object>();
		    params.put("number", number);
		    params.put("templateId", 7217);
		    String[] templateParams = {testbtn, "5分钟内有效"};
		    params.put("templateParams", templateParams);
		    //调用接口发送短信
			String result = client.send(params);
			json = JSONObject.parseObject(result);
			if(json.getIntValue("code") != 0){//发送短信失败
				renderData(response, "获取失败:"+json.getString("data"));
				return; 
			}
			//将验证码存到session中,同时存入创建时间
			HttpSession session = request.getSession();
			SessionUtil.save(session, number, testbtn, 5 * 60);
			//renderData(response, "success");
			return ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderData(response, "fail");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	protected void renderData(HttpServletResponse response, String data){
		try {
			response.setContentType("text/plain;charset=UTF-8");
			response.getWriter().write(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
